import axios from 'axios'
import qs from 'qs'
import {APIPATH} from './config'
import {toast} from './toast'

let instance = axios.create({
  timeout: 30000,
  baseURL: process.env.NODE_ENV === 'development' ? APIPATH : ''
})

instance.interceptors.request.use(
  config => {
    if (
      config.method.toLocaleUpperCase() === 'POST' ||
      config.method.toLocaleUpperCase() === 'PUT' ||
      config.method.toLocaleUpperCase() === 'DELETE'
    ) {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  response => {
    if (response.data && response.data.success === false) {
      return Promise.reject(response.data)
    }
    return response.data
  },
  error => {
    toast(error.toString())
    return Promise.reject(error)
  }
)

const get = (url, params, config = {}) => {
  return instance.get(url, {
    params: params,
    ...config
  })
}

const post = (url, data, config = {}) => {
  return instance.post(url, data, config)
}

export default {
  install (Vue) {
    Object.defineProperties(Vue.prototype, {
      $reqGet: {
        value: get
      },
      $reqPost: {
        value: post
      }
    })
  }
}
